<?php


/*
 *  通过qq号获取昵称和头像链接
 *
 */
function getNicknameToQQ($qq){
    if (!$qq || !preg_match('|^[1-9]\d{4,10}$|i',$qq)){
        return json(['code'=>0,'msg'=>'qq格式错误']);
    }

    //昵称
    $nickname=file_get_contents('http://users.qzone.qq.com/fcg-bin/cgi_get_portrait.fcg?uins='.$qq);
    if (strstr($nickname,'portraitCallBack')){
        //查到了
        $nickname=mb_convert_encoding ($nickname,'UTF-8','GBK');
        $nickname=trim($nickname,'portraitCallBack()');
        $nickname=json_decode($nickname,true);
        if(empty($nickname[$qq][6])){
            $nickname[$qq][6]='游客';
        }
        //头像地址
        $image='http://q.qlogo.cn/headimg_dl?dst_uin='.$qq.'&spec=100';
        return json(['code'=>1,'msg'=>'获取成功','data'=>$nickname[$qq][6],'image'=>$image]);

    }else{
        //获取昵称失败
        return json(['code'=>0,'msg'=>'获取昵称失败']);
    }


}
/*
 * 生成随机唯一邀请码/优惠码
 * $len 要生成的长度
 */
function make_coupon_card($len=6) {
    $code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
    $rand = $code[rand(0,25)]
        .strtoupper(dechex(date('m')))
        .date('d').substr(time(),-5)
        .substr(microtime(),2,5)
        .sprintf('%02d',rand(0,99));
    for(
        $a = md5( $rand, true ),
        $s = '0123456789ABCDEFGHIJKLMNOPQRSTUV',
        $d = '',
        $f = 0;
        $f < $len;
        $g = ord( $a[ $f ] ),
        $d .= $s[ ( $g ^ ord( $a[ $f + 8 ] ) ) - $g & 0x1F ],
        $f++
    );
    return $d;
}

/**
 * 多个数组的笛卡尔积
 *
 * @param unknown_type $data
 */
function combineDika() {
    $data = func_get_args();
    $data = current($data);
    $cnt = count($data);
    $result = array();
    $arr1 = array_shift($data);
    foreach($arr1 as $key=>$item)
    {
        $result[] = array($item);
    }

    foreach($data as $key=>$item)
    {
        $result = combineArray($result,$item);
    }
    return $result;
}
/**
 * 两个数组的笛卡尔积
 * @param unknown_type $arr1
 * @param unknown_type $arr2
 */
function combineArray($arr1,$arr2) {
    $result = array();
    foreach ($arr1 as $item1)
    {
        foreach ($arr2 as $item2)
        {
            $temp = $item1;
            $temp[] = $item2;
            $result[] = $temp;
        }
    }
    return $result;
}
/*
 * 根据ip查询地理位置
 *
 */
function seePositionToIp($ip){
    $url='http://ip.taobao.com/service/getIpInfo.php?ip=' . $ip;
    $curl = curl_init(); // 启动一个CURL会话
    curl_setopt($curl, CURLOPT_URL, $url);
    curl_setopt($curl, CURLOPT_HEADER, 0);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); // 跳过证书检查
    curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);  // 从证书中检查SSL加密算法是否存在
    $tmpInfo = curl_exec($curl);     //返回api的json对象
    //关闭URL请求
    curl_close($curl);
    return $tmpInfo;    //返回json对
}


/*
 * 获取用户数据库信息
 */
function lemon_get_user_data($user_id){
    $data=\think\Db::name('user')->find($user_id);
    if($data){
        $data['more']=json_decode($data['more'],true);
    }
    return $data;
}


function curlPost($url='',$post_data=array()){
    if(empty($url) || empty($post_data)){
        return false;
    }
    $postUrl=$url;
    $curlPost=$post_data;
    $headers = array("Content-type: application/json;charset='utf-8'","Accept: application/json");
    $ch=curl_init();//初始化curl
    curl_setopt($ch,CURLOPT_URL,$postUrl);//抓取指定网页
    curl_setopt($ch,CURLOPT_HEADER,0);//设置header
    curl_setopt($ch,CURLOPT_HTTPHEADER,$headers);
    curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);//要求结果未字符串且输出到屏幕上
    curl_setopt($ch,CURLOPT_POST,1);//post提交
    curl_setopt($ch,CURLOPT_POSTFIELDS,json_encode($curlPost));//提交数据
    $data=curl_exec($ch);//运行
    curl_close($ch);
    return $data;
}

/**
 * 商城获取规格名称
 * @$goods_id 商品id
 * @$spec_id 规格id
 */
function getSpecName($goods_id,$spec_id){
    $spec = model('MallSpec')->where(array('id'=>$spec_id))->field('spec_name')->find();
    return $spec['spec_name'];
}
/**
 * 商城获取规格项图片
 * @$goods_id 商品id
 * @$item_id 规格项id
 */
function getItemImg($goods_id,$item_id){
    $img = model('MallSpecImg')->where(array("goods_id"=>$goods_id,"spec_item_id"=>$item_id))->find();
    return $img['img'];
}

/**
 * 查看某个用户购物车中商品的数量
 * @param type $user_id
 * @param type $session_id
 * @return type 购买数量
 */
function cart_goods_num($user_id = 0,$session_id = '')
{
    $where = " session_id = '$session_id' ";
    $user_id && $where .= " or user_id = $user_id ";
    // 查找购物车数量

    $cart_count =  \think\Db::name('mall_cart')->where($where)->sum('goods_num');
    $cart_count = $cart_count ? $cart_count : 0;
    return $cart_count;
}
/**
 * 获取省市联动的 省级数据 1
 * @param $type  0为移动端所需要的数据格式  1为纯省级数组
 */
function get_provs_data($type = 0){
    $cache_name = CMS_NAME . '_provs_data_' . $type;
    $data = cache($cache_name);

    if(!$data){
        if($type == 0){
            $data = \think\Db::name('region')->where(array('parent_id'=>0,'level'=> 1))->field('id as value,name as text')->select()->toArray();

        }else{
            $data = \think\Db::name('region')->where(array('parent_id'=>0,'level'=> 1))->field('id,name')->select()->toArray();
        }
        cache($cache_name,$data);
    }
    return $data;
}
/**
 *  获取省市联动的  市级数据 2
 * @param $type  0为移动端所需要的数据格式  1为纯市级数组
 */
function get_city_data($type = 0){
    $cache_name = CMS_NAME . '_city_data_' . $type;
    $data = cache($cache_name);
    if(!$data){
        $provs_data = get_provs_data();
        $city_data = \think\Db::name('region')->where(array('level'=> 2))->field('id,name,parent_id')->select()->toArray();
        if($type == 0){
            $data = [];
            foreach ($provs_data as $k => $v){
                foreach ($city_data as $kk => $vv){
                    if($v['value'] == $vv['parent_id']){
                        $data[$v['value']][] = ['value' => "{$vv['id']}",'text' => "{$vv['name']}"];
                    }
                }
            }
        }else{
            $data = $city_data;
        }


        cache($cache_name,$data);

    }
    return $data;

}
/**
 *  获取省市联动的  县级数据 3
 *  @param $type  0为移动端所需要的数据格式  1为纯县级数组
 */
function get_dists_data($type = 0){
    $cache_name = CMS_NAME . '_dists_data_' . $type;
    $data = cache($cache_name);
    if(!$data){
        $dists_data = \think\Db::name('region')->where(array('level'=> 3))->field('id,name,parent_id')->select()->toArray();
        if($type == 0){
            $city_data = get_city_data(1);

            $data = [];
            foreach ($city_data as $k => $v){

                foreach ($dists_data as $kk => $vv){
                    if($v['id'] == $vv['parent_id']){
                        $data[$v['id']][] = ['value' => "{$vv['id']}",'text' => "{$vv['name']}"];
                    }
                }
            }
        }else{
            $data = $dists_data;
        }


        cache($cache_name,$data);

    }

    return $data;

}

/**
 * 获取商品库存
 * @param type $goods_id 商品id
 * @param type $key  库存规格规则
 */
function getGoodNum($goods_id,$key)
{
    if(!empty($key)){
        return  \think\Db::name('mall_goods_sku')->where(array("goods_id"=>$goods_id,"item_path"=>$key))->column('store_count');
    }else{
        return  \think\Db::name("mall_goods")->where(array("id"=>$goods_id))->column('store_count');
    }
}
/**
 * 获取商品运费
 * @param type $express_id 运费模板id
 * @param type $city_id 收货地址的省级id
 * @param type $weight 商品重量
 */
function getGoodExpress($express_id,$city_id,$weight=0){
    //①查出不包邮地区
    //   直接查询包邮地区是否存在
    //   如果存在则直接返回运费和续重费用
    //   如果不存在则去查询全国运费和续重费用

    $express_delivery_city = \think\Db::name('mall_express_delivery_city')->where(['t_id'=>$express_id,'city_id'=>$city_id])->find();
    if(is_null($express_delivery_city)){

        $express_delivery_city = \think\Db::name('mall_express_template')->field('id,charging_type,ykg,ymoney,addkg,addmoney,express_type')->find($express_id);
    }
    //根据商品重量计算费用  不满1000g的按1000g进行续重 向上取整
    if($weight <= $express_delivery_city['ykg']){
        $express_money = $express_delivery_city['ymoney'];
    }else{
        $weight = $weight-$express_delivery_city['ykg'];
        $addkg = ceil($weight/$express_delivery_city['addkg']);
        $express_money = ($addkg*$express_delivery_city['addmoney']) + $express_delivery_city['ymoney'];  //要加上首重价格
    }

    return round($express_money,2);
}
function get_http_type(){
    $http_type = ((isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on') || (isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https')) ? 'https://' : 'http://';
    return $http_type;
}

/**
 * 获取商品分类
 *
 */
function get_mall_category(){
    $categoryModel  = new \app\mall\model\MallGoodsCategoryModel();
    $category_data  = $categoryModel->getParentCategory(0);
    return $category_data;
}